#include "bsp_usb.h"
#include "bsp.h"
#if (CONFIG_HAL_USB_HOST_MODULE_ENABLED)
#include "usbh_core.h"
#endif



/* BSP-USB */

/* define */
#define USB_PWR_PORT   GPIOB
#define USB_PWR_PIN    GPIO_PIN_10




/* static var */
static PCD_HandleTypeDef usb_device_pcd;
static HCD_HandleTypeDef usb_host_hcd;


/* static func */


void OTG_FS_IRQHandler(void)
{
#if (CONFIG_HAL_USB_DEVICE_MODULE_ENABLED)
    HAL_PCD_IRQHandler(&usb_device_pcd);
#endif

#if (CONFIG_HAL_USB_HOST_MODULE_ENABLED)
    HAL_HCD_IRQHandler(&usb_host_hcd);
#endif
}



/* export func */



void bsp_usb_init(void)
{
    GPIO_InitTypeDef GPIO_InitStruct = {0};

    /* GPIO - USB_POWER:PB10 */
    __HAL_RCC_GPIOB_CLK_ENABLE();
    GPIO_InitStruct.Pin = USB_PWR_PIN;
    GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
    GPIO_InitStruct.Pull = GPIO_PULLUP;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_MEDIUM;
    HAL_GPIO_Init(USB_PWR_PORT, &GPIO_InitStruct);
    bsp_usb_power_off();

    /* GPIO - USB_DP, USB_DM */
    __HAL_RCC_GPIOA_CLK_ENABLE();
    GPIO_InitStruct.Pin = GPIO_PIN_11 | GPIO_PIN_12;
    GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
    GPIO_InitStruct.Pull = GPIO_NOPULL;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
    GPIO_InitStruct.Alternate = GPIO_AF10_OTG1_FS;
    HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

    /* USB-FS */
    HAL_PWREx_EnableUSBVoltageDetector();
    __HAL_RCC_USB_OTG_FS_CLK_ENABLE();
    HAL_NVIC_SetPriority(OTG_FS_IRQn, 10, 0);   /* 优先级设置为抢占1,子优先级0 */
    HAL_NVIC_EnableIRQ(OTG_FS_IRQn);            /* 使能OTG FS中断 */


}

void bsp_usb_power_on(void)
{
    bsp_gpio_pin_set(USB_PWR_PORT, USB_PWR_PIN);
}

void bsp_usb_power_off(void)
{
    bsp_gpio_pin_clr(USB_PWR_PORT, USB_PWR_PIN);
}





HCD_HandleTypeDef *bsp_usb_host_get_hcd(void)
{
    return &usb_host_hcd;
}


PCD_HandleTypeDef *bsp_usb_device_get_pcd(void)
{
    return &usb_device_pcd;
}

uint8_t bsp_usb_host_is_connect(void)
{
#if (CONFIG_HAL_USB_HOST_MODULE_ENABLED)

    USBH_HandleTypeDef *phost = usb_host_hcd.pData;

    return (phost->device.is_connected == 1) ? 1 : 0;
#else
    return 0;
#endif
}


